package dk.marten.ibdrecord;

import java.text.SimpleDateFormat;
import java.util.List;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

public class ExportData extends Activity {
	
	private String baseurl = "http://www.marten.dk/wp_apps/SendIBDData.ashx";
	private static String Comma = ",";
	private static String Wrapper = "\"";
	private TextView emailTv,svar;
	private SharedPreferences settings;
	
	public static String SharedPreferencesName = "IBDRecord";
	
	private boolean gotWifiAccess = false;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_export_data);

		emailTv = (TextView) findViewById(R.id.emailInput);
		svar = (TextView) findViewById(R.id.svar);
		
		settings = getSharedPreferences(SharedPreferencesName, 0);
	       
	    emailTv.setText(settings.getString("email", ""));
	    svar.setText("");
		
	    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
		
		NetworkInfo networkInfo = null; 
	    if (conMan != null) { 
	        networkInfo = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
	    }
	  	 gotWifiAccess = (networkInfo == null) ? false : networkInfo.isConnected();
	  	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_export_data, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.exportDoExportBtn:
			doExport();
			break;
		case R.id.exportCancelBtn:
			finish();
			break;
		
		}
        return true;
    }

	 public void doExport(View view) {
		 doExport();
	 
	 }
	
	 public void doExport() {

		 String email = (String) emailTv.getText().toString();

		 if(email == null || email.trim().equals("")){
			 svar.setText(R.string.exportMailError);
			 return;
		 }
		 
	      SharedPreferences.Editor editor = settings.edit();
	      editor.putString("email", email);
	      editor.commit();
	      
		 if(!gotWifiAccess){
			 svar.setText(R.string.exportMailError);
			 return;
		 }
		 
		 RadioButton csvRB = (RadioButton) findViewById(R.id.csvRBtn);
		 RadioButton skvRB = (RadioButton) findViewById(R.id.skvRBtn);
         if (csvRB.isChecked() == true)
         {
        	 ExportData.Comma = ",";
        	 ExportData.Wrapper = "\"";
         }
         else if (skvRB.isChecked() == true)
         {
        	 ExportData.Comma = ";";
        	 ExportData.Wrapper = "";
        }

		Resources res = getResources();
		DBAccess dbAccess= new DBAccess(this);
		dbAccess.open();

		String toiletcsv = res.getString(R.string.titelDato) + ExportData.Comma + res.getString(R.string.titelKonsistens) + ExportData.Comma + res.getString(R.string.titelSlim) + ExportData.Comma + res.getString(R.string.titelBlod) + ExportData.Comma + res.getString(R.string.titelTrang) + "\n";
		String tilstandcsv = res.getString(R.string.titelDato)  + ExportData.Comma + res.getString(R.string.titelTilstand)  + ExportData.Comma + res.getString(R.string.titelFatigue) + ExportData.Comma + res.getString(R.string.titelSmerte) + ExportData.Comma + res.getString(R.string.titelStress) + "\n";
		
		List<TilstandData> tilData = dbAccess.getAllTilstandData();		 
		List<ToiletData> toiData = dbAccess.getAllToiletData();

        for (ToiletData t : toiData)
        {
        	toiletcsv += DateFormat.format("yyyy-MM-dd hh:mm",t.getDato()) + ExportData.Comma + t.getKonsistens() + ExportData.Comma + t.getSlim() + ExportData.Comma + t.getBlod() + ExportData.Comma + t.getTrang() + "\n";
        }

		for (TilstandData t : tilData)
		{
			tilstandcsv += DateFormat.format("yyyy-MM-dd hh:mm",t.getDato()) + ExportData.Comma + t.getTilstand() + ExportData.Comma + t.getFatigue() + ExportData.Comma + t.getSmerte() + ExportData.Comma + t.getStress() + "\n";
		}
		dbAccess.close();
		
		RequestParams params = new RequestParams();
		params.put("toiletData", toiletcsv);
		params.put("tilstandData", tilstandcsv);
		params.put("mail", email);
		
		AsyncHttpClient client = new AsyncHttpClient();
		 
		client.post(baseurl, params, new AsyncHttpResponseHandler() {
			 @Override
			public void onSuccess(String response) {
				if(response.trim() == "Succes"){
				    svar.setText(R.string.exportSucces);
				}else{
				    svar.setText(R.string.exportError);
					Log.e("MOE","Noget gik galt: \""+response+"\"");
				}
			}
		});		 
		 
	 }

}
